import React, { useState } from 'react';
import { message, Spin, Row, Col } from 'antd';
import { TRDefault } from '@/components/index.js';
import { HttpCode } from '#/utils/contacts.js';
//@ts-ignore
import { export_json_sheets_to_excel } from '@/utils/fileExport.js';
//@ts-ignore
import { InfoCircleOutlined } from '#/utils/antdIcons';
import {
  postQueryPriceDiffList,
  postQueryNodePriceSumGridList,
  postQueryNodeStationList,
} from './service';
import { DEFAULT_HINT_TEXT, DEFAULT_TITLE_TEXT, NODE_DEFAULT_HINT_TEXT } from './dictionary';
import { Header, List, ExplainTitle, NodePriceSumGridList, EchartsModal } from './components/index';
import type {
  IProps,
  IFormValue,
  IStationNodeListType,
  IPriceDiffListDataType,
  IEchartParamsType,
} from './type';
import styles from './index.less';
import moment from 'moment';

export default (props: IProps) => {
  const { power, buttonPermissions } = props;
  const [formValue, setFormValue] = useState<any>({});
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [isError, setIsError] = useState<boolean>(false);
  const [isRightLoading, setIsRightLoading] = useState<boolean>(false);
  const [isRightError, setIsRightError] = useState<boolean>(false);
  const [nodeStationList, setNodeStationList] = useState<IStationNodeListType[]>([]); // 配置列表原始数据
  const [priceDiffList, setPriceDiffList] = useState<IPriceDiffListDataType[]>([]); // 通道阻塞引起价差统计
  const [checkedPriceDiffInfo, setCheckedPriceDiffInfo] = useState<IFormValue>({}); //选中的阻塞引起价差信息
  const [nodePriceSumGridList, setNodePriceSumGridList] = useState<any[]>([]); //通道阻塞-节点价差相关情况

  // 获取配置列表
  const getNodeStationList = async (provinceId: string, marketId: string) => {
    const res = await postQueryNodeStationList({
      checkPower: true,
      provinceId,
      marketId,
    });
    if (res && res.statusCode === HttpCode.SUCCESS) {
      setNodeStationList(res?.data || []);
    } else {
      setNodeStationList([]);
      message.error(res?.message || '系统异常');
    }
  };

  // 查询价差相关情况-格子列表数据
  const queryNodePriceSumGridList = async (data: IFormValue) => {
    setIsRightLoading(true);
    const { nodeName, ...rest } = data;
    const res = await postQueryNodePriceSumGridList({ ...rest });
    if (res && res.statusCode === HttpCode.SUCCESS) {
      setIsRightError(false);
      setNodePriceSumGridList(res?.data || []);
    } else {
      setIsRightError(true);
      message.error(res?.message || '系统异常');
    }
    setIsRightLoading(false);
  };

  // 查询
  const onSearch = async (values: any, type: string) => {
    const { beginDate, endDate, marketId, provinceId, nodeIdList } = values;
    setFormValue({ ...values });
    if (!nodeIdList?.length) {
      setNodeStationList([]);
      setNodePriceSumGridList([]);
    } else {
      setIsLoading(true);
      const res = await postQueryPriceDiffList({
        beginDate,
        endDate,
        marketId,
        provinceId,
        nodeIdList,
        isAppointedDay: type === 'isFirst',
      });
      getNodeStationList(provinceId, marketId);
      if (res && res.statusCode === HttpCode.SUCCESS) {
        setIsError(false);
        const _priceDiffList = res?.data || [];
        setPriceDiffList(res?.data || []);
        if (_priceDiffList.length) {
          const _checkedPriceDiffInfo: IFormValue = {
            nodeIdList,
            marketId,
            provinceId,
            beginDate: _priceDiffList[0]?.calendarDate,
            endDate: _priceDiffList[0]?.calendarDate,
            blockName: _priceDiffList[0]?.values ? _priceDiffList[0]?.values[0]?.blockName : '',
            nodeName: formValue?.nodeName,
          };
          setCheckedPriceDiffInfo(_checkedPriceDiffInfo);
          queryNodePriceSumGridList(_checkedPriceDiffInfo);
        }
      } else {
        setIsError(true);
        message.error(res?.message || '系统异常');
      }
    }
    setIsLoading(false);
  };

  // 选择不同的价差
  const onClickPriceDiff = (data: IFormValue) => {
    const _checkedPriceDiffInfo: IFormValue = {
      nodeIdList: formValue?.nodeIdList,
      provinceId: formValue?.provinceId,
      marketId: formValue?.marketId,
      nodeName: formValue?.nodeName,
      beginDate: data?.beginDate,
      endDate: data?.endDate,
      blockName: data?.blockName,
    };
    setCheckedPriceDiffInfo(_checkedPriceDiffInfo);
    queryNodePriceSumGridList(_checkedPriceDiffInfo);
  };

  // 显示Eharts 图
  const onShow = async (params: IEchartParamsType) => {
    const { nodeX, nodeY } = params;
    const _nodeXName = nodeStationList.find((item) => item.nodeId === nodeX);
    const _nodeYName = nodeStationList.find((item) => item.nodeId === nodeY);
    await EchartsModal.show({
      params,
      nodeXName: _nodeXName?.nodeNameAlias,
      nodeYName: _nodeYName?.nodeNameAlias,
    });
  };

  // 导出文件
  const handleExportFile = () => {
    const sheetData1: any[] = [];
    const header1 = ['日期'];
    priceDiffList.forEach((item, index) => {
      const _arr = [];
      _arr.push(item?.calendarDate);
      item?.values?.forEach((element) => {
        _arr.push(element?.diffPriceSum);
        if (index === 0) {
          header1.push(element?.blockName || '');
        }
      });
      sheetData1.push(_arr);
    });
    const sheetData2: any[] = [];
    const header2 = [''];
    nodePriceSumGridList.forEach((item, index) => {
      const _arr = [];
      const nodeStation = nodeStationList.find((element) => {
        return element.nodeId === item.nodeId;
      });
      _arr.push(nodeStation?.nodeNameAlias);
      item.values?.forEach((element) => {
        const _nodeStation = nodeStationList.find((i) => {
          return element.nodeId === i.nodeId;
        });
        if (index === 1) {
          header2.push(_nodeStation?.nodeNameAlias || '');
        }
        _arr.push(element.value);
      });
      sheetData2.push(_arr);
    });
    const params = {
      list: [
        {
          data: sheetData1,
          sheetName: `通道阻塞引起价差统计-${checkedPriceDiffInfo.nodeName}`,
          header: header1,
        },
        {
          data: sheetData2,
          sheetName: `${moment(checkedPriceDiffInfo.beginDate).format('YYYYMMDD')}-${
            checkedPriceDiffInfo?.blockName
          }通道阻塞-${checkedPriceDiffInfo?.nodeName}价差相关情况`,
          header: header2,
        },
      ],
      name: `阻塞-价差相关性_${moment(formValue?.beginDate).format('YYYYMMDD')}-${moment(
        formValue?.endDate,
      ).format('YYYYMMDD')}`,
      type: 'xlsx',
    };
    export_json_sheets_to_excel(params);
  };

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <div className={styles.header}>
          <Header
            power={power}
            buttonPermissions={buttonPermissions}
            onSearch={onSearch}
            handleExportFile={handleExportFile}
          />
        </div>
        <div className={styles.main}>
          {isLoading ? (
            <Spin />
          ) : isError ? (
            <TRDefault type={'error'} message={'系统异常'} />
          ) : priceDiffList?.length ? (
            <Row className={styles.bottom} wrap={false}>
              <Col className={styles.left} span={10}>
                <div className={styles.leftHeader}>
                  <ExplainTitle title={DEFAULT_TITLE_TEXT} hintText={DEFAULT_HINT_TEXT} />
                </div>
                <div className={styles.leftBottom}>
                  <List
                    dataSource={priceDiffList}
                    checkedPriceDiffInfo={checkedPriceDiffInfo}
                    onClick={onClickPriceDiff}
                  />
                </div>
              </Col>
              <Col className={styles.right} span={14}>
                {isRightLoading || isRightError ? null : (
                  <div className={styles.rightHeader}>
                    <div className={styles.leftHint}>
                      {checkedPriceDiffInfo.beginDate &&
                      checkedPriceDiffInfo?.blockName &&
                      checkedPriceDiffInfo?.nodeName ? (
                        <ExplainTitle
                          title={`${moment(checkedPriceDiffInfo.beginDate).format('YYYYMMDD')}-${
                            checkedPriceDiffInfo?.blockName
                          }通道阻塞-${checkedPriceDiffInfo?.nodeName}价差相关情况`}
                          hintText={NODE_DEFAULT_HINT_TEXT}
                        />
                      ) : null}
                    </div>
                    <div className={styles.rightHint}>
                      <div className={styles.hintText}>
                        <InfoCircleOutlined className={styles.hint} />
                      </div>
                      <div className={styles.text}>点击方格可查看节点价差及通道阻塞价差详情</div>
                    </div>
                  </div>
                )}
                {isRightLoading ? (
                  <Spin />
                ) : isRightError ? (
                  <TRDefault type={'error'} message={'系统异常'} />
                ) : nodePriceSumGridList.length ? (
                  <div className={styles.rightBottom}>
                    <NodePriceSumGridList
                      nodePriceSumGridList={nodePriceSumGridList}
                      nodeStationList={nodeStationList}
                      checkedPriceDiffInfo={checkedPriceDiffInfo}
                      onShow={onShow}
                    />
                  </div>
                ) : (
                  <TRDefault type={'emptysm'} message={'暂无数据'} />
                )}
              </Col>
            </Row>
          ) : (
            <TRDefault type={'emptysm'} message={'暂无数据'} />
          )}
        </div>
      </div>
    </div>
  );
};
